package com.business.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.business.dao.*;
import com.business.domain.*;
import com.business.domain.CarBrandExample.Criteria;
import com.business.service.CarService;
import com.sys.Utils.ExcelUtil;
import com.sys.Utils.FileUtils;
import com.sys.dao.AdminProvinceMapper;
import com.sys.dao.DictItemMapper;
import com.sys.domain.AdminProvince;
import com.sys.domain.AdminProvinceExample;
import com.sys.domain.DictItem;
import com.sys.domain.DictItemExample;
import com.sys.result.PageParam;
import com.sys.result.RequestPageVo;
import com.sys.result.RequestResultVo;
import com.sys.result.ResultVo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

@Service("carService")
public class CarServiceImpl implements CarService {
    private static final Logger logger = LoggerFactory.getLogger(CarServiceImpl.class);

    @Resource
    private CarBrandMapper carBrandMapper;
    @Resource
    private CarModelMapper carModelMapper;
    @Resource
    private CarSeriesMapper carSeriesMapper;
    @Resource
    private DictItemMapper dictItemMapper;
    @Resource
    private AdminProvinceMapper adminProvinceMapper;
    @Resource
    private CarRefProvinceMapper carRefProvinceMapper;

    @Resource
    private ActivitiesCarMapper activitiesCarMapper;

    @Override
    public RequestPageVo<CarBrand> getBrandList(PageParam param, CarBrand brand) {
        RequestPageVo<CarBrand> vo = new RequestPageVo<CarBrand>();

        CarBrandExample example = new CarBrandExample();
        example.setOrderByClause("creatime desc");
        Criteria create = example.createCriteria();
        if (!StringUtils.isEmpty(brand.getName())) {
            create.andNameLike("%" + brand.getName() + "%");
        }
        if (brand.getIsDelete() != null) {
            create.andIsDeleteEqualTo(brand.getIsDelete());
        }
        try {
            int count = carBrandMapper.countByExample(example);
            if (count > 0) {
                example.setStartPage(param.getOffset());
                example.setPageSize(param.getLimit());
                List<CarBrand> list = carBrandMapper.selectByExample(example);
                vo.setRows(list);
                vo.setTotal(count);
            }
        } catch (Exception e) {
            logger.error("getBrandList error", e);
        }
        return vo;
    }

    public List<CarBrand> getAllCarBrand() {
        CarBrandExample example = new CarBrandExample();
        example.setOrderByClause("initial");
        Criteria create = example.createCriteria();
        create.andIsDeleteEqualTo(false);
        return carBrandMapper.selectByExample(example);
    }

    /**
     * 获取品牌page
     */
    public RequestPageVo<CarSeriesVo> getSeriesList(PageParam param, CarSeries series) {
        RequestPageVo<CarSeriesVo> vo = new RequestPageVo<CarSeriesVo>();

        CarSeriesExample example = new CarSeriesExample();
        example.setOrderByClause("creatime desc");
        com.business.domain.CarSeriesExample.Criteria create = example.createCriteria();
        if (series.getBrandId() != null && series.getBrandId() > 0) {
            create.andBrandIdEqualTo(series.getBrandId());
        }
        if (!StringUtils.isEmpty(series.getName())) {
            create.andNameLike("%" + series.getName() + "%");
        }
        try {
            int count = carSeriesMapper.countByExample(example);
            if (count > 0) {
                example.setStartPage(param.getOffset());
                example.setPageSize(param.getLimit());
                List<CarSeriesVo> list = carSeriesMapper.selectByExample(example);
                if (!CollectionUtils.isEmpty(list)) {
                    for (CarSeriesVo carSeriesVo : list) {
                        Integer brandId = carSeriesVo.getBrandId();
                        CarBrand brand = carBrandMapper.selectByPrimaryKey(brandId);
                        carSeriesVo.setBrandName(brand.getName());
                    }
                }
                vo.setRows(list);
                vo.setTotal(count);
            }
        } catch (Exception e) {
            logger.error("getBrandList error", e);
        }
        return vo;

    }

    @Override
    public ResultVo saveOrUpdateBrand(CarBrand brand, MultipartFile contractFile) {
        ResultVo result = new ResultVo();
        // 首字母转换大写
        brand.setInitial(brand.getInitial().toUpperCase());

        CarBrandExample example = new CarBrandExample();
        Criteria criteria = example.createCriteria();
        criteria.andNameEqualTo(brand.getName());
        criteria.andIsDeleteEqualTo(false);
        List<CarBrand> list = carBrandMapper.selectByExample(example);
        try {
            if (brand.getId() == null) {

                if (list != null && list.size() > 0) {// 判断品牌名字是否重复
                    result.setSuccess(false);
                    result.setErrorMessage("品牌名称已存在，请勿重复添加！");
                    return result;
                } else {
                    if (contractFile != null) {
                        String imgUrl = FileUtils.uploadImg(contractFile);
                        if (imgUrl == null) {
                            result.setSuccess(false);
                            result.setErrorMessage("请上传正确格式的图片");
                        } else {
                            brand.setImageUrl(imgUrl);
                            // 添加
                            brand.setCreatime(new Date());
                            carBrandMapper.insertSelective(brand);
                        }
                    } else {
                        // 添加
                        brand.setCreatime(new Date());
                        carBrandMapper.insertSelective(brand);
                    }

                }
            } else {
                for (CarBrand carBrand : list) {
                    if (!carBrand.getId().equals(brand.getId())) {// 名称修改了
                        if (list.size() > 0) {
                            result.setSuccess(false);
                            result.setErrorMessage("品牌名称已存在，请勿重复！");
                            return result;
                        }
                    }
                }
                if (contractFile != null) {
                    String imgUrl = FileUtils.uploadImg(contractFile);
                    if (imgUrl == null) {
                        result.setSuccess(false);
                        result.setErrorMessage("请上传正确格式的图片");
                    } else {
                        brand.setImageUrl(imgUrl);
                        carBrandMapper.updateByPrimaryKeySelective(brand);
                        result.setSuccess(true);
                    }
                } else {
                    carBrandMapper.updateByPrimaryKeySelective(brand);
                    result.setSuccess(true);
                }

            }

        } catch (Exception e) {
            logger.error("updateBrand error", e);
            result.setSuccess(false);
        }
        return result;
    }

    @Override
    public ResultVo deleteById(Integer id, String type) {
        ResultVo result = new ResultVo();
        try {
            String carType = "车型";
            if ("brand".equals(type)) {
                carType = "品牌";
                // 删除品牌 判断品牌下是否有车系 如果有就不能删除
                CarSeriesExample example = new CarSeriesExample();
                com.business.domain.CarSeriesExample.Criteria criteria = example.createCriteria();
                criteria.andBrandIdEqualTo(id);
                List<CarSeriesVo> list = carSeriesMapper.selectByExample(example);
                if (list.size() > 0) {
                    result.setSuccess(false);
                    result.setErrorMessage("该品牌下存在车系，请先删除车系！");
                    return result;
                } else {
                    carBrandMapper.deleteByPrimaryKey(id);

                    result.setSuccess(true);
                }
            } else if ("series".equals(type)) {
                carType = "车系";
                // 删除车系 判断车系下是否有车型 如果有就不能删除
                CarModelExample example = new CarModelExample();
                com.business.domain.CarModelExample.Criteria criteria = example.createCriteria();
                criteria.andSeriesIdEqualTo(id);
                List<CarModelVo> list = carModelMapper.selectByExample(example);
                if (list.size() > 0) {
                    result.setSuccess(false);
                    result.setErrorMessage("该车系下存在车型，请先删除车型！");
                    return result;
                } else {
                    carSeriesMapper.deleteByPrimaryKey(id);
                    result.setSuccess(true);
                }
            } else {
                // 删除车型
                CarModel model = new CarModel();
                model.setId(id);
                model.setIsDelete(true);
                carModelMapper.updateByPrimaryKeySelective(model);
            }
            ActivitiesCarExample activeexample = new ActivitiesCarExample();
            com.business.domain.ActivitiesCarExample.Criteria createCriteria = activeexample.createCriteria();
            createCriteria.andCarIdEqualTo(id);
            createCriteria.andCarTypeEqualTo(carType);
            activitiesCarMapper.deleteByExample(activeexample);
        } catch (Exception e) {
            logger.error("deleteById error", e);
        }
        return result;
    }

    @Override
    public ResultVo saveOrUpdateSeries(CarSeries series) {
        ResultVo result = new ResultVo();
        CarSeriesExample example = new CarSeriesExample();
        com.business.domain.CarSeriesExample.Criteria criteria = example.createCriteria();
        criteria.andNameEqualTo(series.getName());
        criteria.andIsDeleteEqualTo(false);
        List<CarSeriesVo> list = carSeriesMapper.selectByExample(example);
        try {
            if (series.getId() == null) {

                if (list != null && list.size() > 0) {// 判断品牌名字是否重复
                    result.setSuccess(false);
                    result.setErrorMessage("车系名称已存在，请勿重复添加！");
                    return result;
                } else {
                    // 添加
                    series.setCreatime(new Date());
                    carSeriesMapper.insertSelective(series);
                }
            } else {
                for (CarSeriesVo carSeriesVo : list) {
                    if (!carSeriesVo.getId().equals(series.getId())) {// 名称修改了
                        if (list.size() > 0) {
                            result.setSuccess(false);
                            result.setErrorMessage("车系名称已存在，请勿重复！");
                            return result;
                        }
                    }
                }
                carSeriesMapper.updateByPrimaryKeySelective(series);
                result.setSuccess(true);
            }
        } catch (Exception e) {
            logger.error("saveOrUpdateSeries error", e);
        }
        return result;
    }

    @Override
    public RequestPageVo<CarModelVo> getModelList(PageParam param, CarModel model, Integer brandId) {
        RequestPageVo<CarModelVo> vo = new RequestPageVo<CarModelVo>();
        CarModelExample example = new CarModelExample();
        example.setOrderByClause("creatime desc");
        com.business.domain.CarModelExample.Criteria create = example.createCriteria();
        if (brandId != null && brandId != 0) {
            List<Integer> seriesIdList = getSeriesIdList(brandId);
            create.andSeriesIdIn(seriesIdList);
        }
        if (model.getSeriesId() != null && model.getSeriesId() != 0) {
            create.andSeriesIdEqualTo(model.getSeriesId());
        }

        if (!StringUtils.isEmpty(model.getName())) {
            create.andNameLike("%" + model.getName() + "%");
        }
        if (model.getIsDelete() != null) {
            create.andIsDeleteEqualTo(model.getIsDelete());
        }
        try {
            int count = carModelMapper.countByExample(example);
            if (count > 0) {
                example.setStartPage(param.getOffset());
                example.setPageSize(param.getLimit());
                List<CarModelVo> list = carModelMapper.selectByExample(example);
                for (CarModelVo carModelVo : list) {
                    Integer seriesId = carModelVo.getSeriesId();
                    CarSeriesVo series = carSeriesMapper.selectByPrimaryKey(seriesId);
                    carModelVo.setSeriesName(series.getName());
                    carModelVo.setBrandId(series.getBrandId());

                    CarBrand brand = carBrandMapper.selectByPrimaryKey(series.getBrandId());
                    carModelVo.setBrandName(brand.getName());
                }
                vo.setRows(list);
                vo.setTotal(count);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("getBrandList error", e);
        }
        return vo;
    }

    @Override
    public ResultVo saveOrUpdateModel(CarModel model) {
        ResultVo result = new ResultVo();
        int count = 0;
        try {
            if (model.getId() != null) {
                // 更新
                model.setUpdateTime(new Date());
                count = carModelMapper.updateByPrimaryKeySelective(model);
            } else {
                // 添加
                model.setCreatime(new Date());
                count = carModelMapper.insertSelective(model);
            }
        } catch (Exception ignored) {

        } finally {
            if (count <= 0) {
                result.setSuccess(false);
                result.setErrorMessage("操作失败！");
            }
        }
        return result;
    }

    private List<Integer> getSeriesIdList(Integer brandId) {
        List<Integer> list = new ArrayList<Integer>();
        CarSeriesExample example = new CarSeriesExample();
        com.business.domain.CarSeriesExample.Criteria create = example.createCriteria();
        create.andBrandIdEqualTo(brandId);
        List<CarSeriesVo> seriesList = carSeriesMapper.selectByExample(example);
        for (CarSeriesVo carSeriesVo : seriesList) {
            list.add(carSeriesVo.getId());
        }
        return list;
    }

    @Override
    public RequestPageVo<CarSeriesVo> getSeriesListByBrandId(Integer brandId) {
        RequestPageVo<CarSeriesVo> vo = new RequestPageVo<CarSeriesVo>();
        CarSeriesExample example = new CarSeriesExample();
        example.setOrderByClause("name");
        com.business.domain.CarSeriesExample.Criteria create = example.createCriteria();
        create.andBrandIdEqualTo(brandId);
        List<CarSeriesVo> seriesList = carSeriesMapper.selectByExample(example);
        vo.setRows(seriesList);
        return vo;
    }

    @Override
    public List<DictItem> getItemByCode(String code) {
        DictItemExample example = new DictItemExample();
        com.sys.domain.DictItemExample.Criteria create = example.createCriteria();
        example.setOrderByClause("item_order desc");
        create.andDictCodeEqualTo(code);

        return dictItemMapper.selectByExample(example);
    }

    @Override
    public ResultVo backById(Integer id) {
        ResultVo result = new ResultVo();
        // 删除车型
        CarModel model = new CarModel();
        model.setId(id);
        model.setIsDelete(false);
        try {
            carModelMapper.updateByPrimaryKeySelective(model);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorMessage("删除失败");
            e.printStackTrace();
        }

        return result;
    }

    @Override
    public ResultVo deleteReaData(Integer id) {
        ResultVo result = new ResultVo();
        try {
            if (id != null) {
                carModelMapper.deleteByPrimaryKey(id);
            }
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorMessage("删除失败");
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public ResultVo addPrice(Integer carModelId, Double price, String address) {
        ResultVo result = new ResultVo();
        try {

            JSONArray parseArray = JSONArray.parseArray(address);
            for (Object object : parseArray) {
                CarRefProvince carRefProvince = new CarRefProvince();

                JSONObject o = (JSONObject) object;
                Integer provinceId = o.getInteger("address");// 省份(id)
                AdminProvince AdminProvince = adminProvinceMapper.selectByPrimaryKey(provinceId.longValue());// 省份

                // 判断该车型在某个地区的价格是否存在，存在则更新 不存在则添加
                CarRefProvinceExample example = new CarRefProvinceExample();
                com.business.domain.CarRefProvinceExample.Criteria criteria = example.createCriteria();
                criteria.andCarIdEqualTo(carModelId);
                criteria.andProvinceIdEqualTo(provinceId);
                List<CarRefProvince> list = carRefProvinceMapper.selectByExample(example);
                if (list.size() > 0) {// 更新
                    for (CarRefProvince c : list) {
                        // carRefProvince.setCarId(carModelId);
                        c.setPrice(price);
                        // carRefProvince.setProvinceId(provinceId);
                        c.setProvinceName(AdminProvince.getProvinceName());
                        carRefProvinceMapper.updateByPrimaryKeySelective(c);

                        result.setSuccess(true);
                    }

                } else {// 添加
                    carRefProvince.setCarId(carModelId);
                    carRefProvince.setPrice(price);
                    carRefProvince.setProvinceId(provinceId);
                    carRefProvince.setProvinceName(AdminProvince.getProvinceName());
                    carRefProvinceMapper.insertSelective(carRefProvince);

                    result.setSuccess(true);
                }

            }
        } catch (Exception e) {
            result.setErrorMessage("操作失败");
            result.setSuccess(false);
        }
        return result;
    }

    @Override
    public RequestPageVo<CarRefProvince> queryPriceByModelId(Integer carModelId) {
        RequestPageVo<CarRefProvince> pageVo = new RequestPageVo<CarRefProvince>();
        try {
            CarRefProvinceExample example = new CarRefProvinceExample();
            com.business.domain.CarRefProvinceExample.Criteria criteria = example.createCriteria();
            criteria.andCarIdEqualTo(carModelId);
            List<CarRefProvince> carRefProvinceList = carRefProvinceMapper.selectByExample(example);
            pageVo.setRows(carRefProvinceList);
        } catch (Exception e) {
            logger.error("queryPriceByModelId error", e);
        }
        return pageVo;
    }

    @Override
    public RequestResultVo<CarModelVo> getModelByModelId(Integer modelId, Integer provinceId) {
        RequestResultVo<CarModelVo> vo = new RequestResultVo<CarModelVo>();
        CarModelVo model = carModelMapper.selectByPrimaryKey(modelId);

        CarRefProvinceExample refExample = new CarRefProvinceExample();
        com.business.domain.CarRefProvinceExample.Criteria createCriteria = refExample.createCriteria();
        createCriteria.andCarIdEqualTo(modelId);
        createCriteria.andProvinceIdEqualTo(provinceId);

        List<CarRefProvince> ref = carRefProvinceMapper.selectByExample(refExample);
        model.setNationwidePrice(model.getGuidePrice());
        Double price = (double) 0;
        for (CarRefProvince carRefProvince : ref) {
            price = carRefProvince.getPrice();
        }

        if (price != 0) {
            model.setGuidePrice(BigDecimal.valueOf(price));
        }
        model.setOldPrice(model.getGuidePrice());// 原价格
        model = this.getPrice(model, provinceId);// 调用活动

        vo.setResult(model);
        return vo;
    }

    @Override
    public RequestPageVo<CarModelVo> getModelListBySeriesId(Integer seriesId) {
        RequestPageVo<CarModelVo> vo = new RequestPageVo<CarModelVo>();
        CarModelExample example = new CarModelExample();
        example.setOrderByClause("name");
        com.business.domain.CarModelExample.Criteria create = example.createCriteria();
        create.andSeriesIdEqualTo(seriesId);
        create.andIsDeleteEqualTo(false);
        List<CarModelVo> list = carModelMapper.selectByExample(example);
        vo.setRows(list);

        return vo;
    }

    @Override
    public List<AdminProvince> getAllProvince() {
        AdminProvinceExample example = new AdminProvinceExample();
        example.setOrderByClause("province_name_efirst");
        return adminProvinceMapper.selectByExample(example);
    }

    @Override
    public ResultVo deletePrice(Integer id) {
        ResultVo vo = new ResultVo();
        try {
            int count = carRefProvinceMapper.deleteByPrimaryKey(id);
            if (count < 0) {
                vo.setSuccess(false);
                vo.setErrorMessage("删除失败");
            }
        } catch (Exception e) {
            vo.setSuccess(false);
            vo.setErrorMessage("删除失败");
            e.printStackTrace();
        }
        return vo;
    }

    @Override
    public Boolean checkedModelName(Integer id, String name, Integer seriesId) {
        CarModelExample example = new CarModelExample();
        com.business.domain.CarModelExample.Criteria createCriteria = example.createCriteria();
        createCriteria.andNameEqualTo(name);
        createCriteria.andSeriesIdEqualTo(seriesId);
        List<CarModelVo> list = carModelMapper.selectByExample(example);
        if (id == null) {
            if (list != null && list.size() > 0) {
                return false;
            }
        }
        if (list != null) {
            if (list.size() > 1) {
                return false;
            } else if (list.size() > 0) {
                if (id != null && !list.get(0).getId().equals(id)) {
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    public CarModelVo getPrice(CarModelVo model, Integer provinceId) {
        Integer  brandId;
        Integer seriesId = model.getSeriesId();
        Integer modelId = model.getId();

        CarSeriesVo seriesr = carSeriesMapper.selectByPrimaryKey(seriesId);
        brandId = seriesr.getBrandId();

        // model.getId();
        ActivitiesCarExample example = new ActivitiesCarExample();
        com.business.domain.ActivitiesCarExample.Criteria createCriteria = example.createCriteria();
        createCriteria.andCarIdEqualTo(model.getId());
        Map<String, String> map = new HashMap<String, String>();
        map.put("id", modelId.toString());
        map.put("cityId", provinceId.toString());
        map.put("type", "车型");
        ActivitiesCar carModel = activitiesCarMapper.getPrice(map);
        BigDecimal price = model.getGuidePrice();
        if (carModel != null) {
            price = jisuanhuodong(carModel, price);
        } else {
            map.put("type", "车系");
            map.put("id", seriesId.toString());
            carModel = activitiesCarMapper.getPrice(map);
            if (carModel != null) {
                price = jisuanhuodong(carModel, price);
            } else {
                map.put("type", "品牌");
                map.put("id", brandId.toString());
                carModel = activitiesCarMapper.getPrice(map);
                if (carModel != null) {
                    price = jisuanhuodong(carModel, price);
                }
            }
        }
        if (!model.getGuidePrice().equals(price)) {
            model.setActivitiesCar(carModel);
        }
        model.setGuidePrice(price);
        return model;
    }

    /**
     * 根据活动类型计算车价格
     */
    private BigDecimal jisuanhuodong(ActivitiesCar car, BigDecimal price) {
        if ("折扣".equals(car.getActivitiesType())) {
            price = BigDecimal.valueOf(car.getActivityRate() * price.doubleValue() / 100);
        } else if ("优惠".equals(car.getActivitiesType())) {
            price = BigDecimal.valueOf(price.doubleValue() - car.getActivityRate());
        }
        return price;
    }

    @Override
    public List<CarBrand> getCarBrandByModel() {
        return carBrandMapper.getCarBrandByModel();
    }

    @Override
    public RequestPageVo<CarSeriesVo> getSeriesListByBrandIdAndModelId(Integer brandId) {
        RequestPageVo<CarSeriesVo> vo = new RequestPageVo<CarSeriesVo>();
        vo.setRows(carSeriesMapper.getSeriesListByBrandIdAndModelId(brandId));
        return vo;
    }

    @Override
    public HSSFWorkbook exportCar() {
        List<CarExcelVo> list = carModelMapper.selectByAll();
        String[] heads = {"品牌","车系","车型名称","指导价","车型级别","排量",
                "马力","进气类型","驱动类型","最高速度","油耗","变速箱档位数","变速箱类型","高度",
                "长度","宽度","重量","质保","车门数量","座位数"};
        HSSFWorkbook hssfWorkbook = null;
        try {
            hssfWorkbook = ExcelUtil.outPutExce("车型数据", heads, list, CarExcelVo.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return hssfWorkbook;
    }

}
